package com.group.nepm.publicSuperviseDataManagement.controller;

import com.group.common.users.NEPSUser;
import com.group.common.utils.MyUtils;
import com.group.nepg.entity.AccurateAqiLevel;
import com.group.nepm.statisticDataManagement.entity.StatisticData;
import com.group.neps.entity.City;
import com.group.neps.entity.Province;
import com.group.neps.entity.RowAqiData;
import com.group.neps.entity.RowAqiLevel;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.util.StringConverter;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;

public class ConfirmAqiDataList {
    @FXML
    private TableView<StatisticData> tableView;

    private ObservableList<StatisticData> tableList = FXCollections.observableArrayList();

    @FXML
    private TableColumn<StatisticData,String> colId;
    @FXML
    private TableColumn<StatisticData,String> colProvince;
    @FXML
    private TableColumn<StatisticData,String> colCity;
    @FXML
    private TableColumn<StatisticData,String> colLevel;
    @FXML
    private TableColumn<StatisticData,String> colDate;
    @FXML
    private TableColumn<StatisticData,String> colTime;
    @FXML
    private TableColumn<StatisticData,String> colNEPG;
    @FXML
    private TableColumn<StatisticData,String> colNEPS;
    @FXML
    private TableColumn<StatisticData,Void> colDetail;



    @FXML
    private ComboBox<Province> cobProvince;
    @FXML
    private ComboBox<City> cobCity;
    @FXML
    private DatePicker datePicker;

    private HashMap<String, Province> provinceMap = new HashMap<>();



    public void initialize() {
        //日期控件使用
        //设置默认值为当前系统时间
        datePicker.setValue(LocalDate.now());

        //设置省、市
        // 设置ComboBox显示方式
        setupComboBoxDisplay();
        // 设置省份选择监听器
        setupProvinceSelectionListener();

        // 初始化列绑定函数
        initializeTableColumns();
        // 加载数据函数
        loadDataToTable();
    }

    private void setupComboBoxDisplay() {
        // 设置省份ComboBox显示
        cobProvince.setConverter(new StringConverter<Province>() {
            @Override
            public String toString(Province province) {
                return province == null ? "" : province.getName();
            }

            @Override
            public Province fromString(String string) {
                return null;
            }
        });

        // 设置城市ComboBox显示
        cobCity.setConverter(new StringConverter<City>() {
            @Override
            public String toString(City city) {
                return city == null ? "" : city.getName();
            }

            @Override
            public City fromString(String string) {
                return null;
            }
        });

        // 填充省份数据
        provinceMap = MyUtils.readFileToHashMap("group/data/location_hashmap.dat");
        ObservableList<Province> provinces = FXCollections.observableArrayList(provinceMap.values());
        cobProvince.setItems(provinces);
    }

    private void setupProvinceSelectionListener() {
        cobProvince.getSelectionModel().selectedItemProperty().addListener((obs, oldProvince, newProvince) -> {
            cobCity.getItems().clear();

            if (newProvince != null) {
                // 获取选中省份的城市列表
                ObservableList<City> cities = FXCollections.observableArrayList(
                        newProvince.getCities().values()
                );
                cobCity.setItems(cities);
            }
        });
    }

    public void clear(ActionEvent actionEvent) {
        cobProvince.getSelectionModel().clearSelection();
        cobCity.getSelectionModel().clearSelection();
        datePicker.setValue(null);

        // 重新加载原始数据到表格
        loadDataToTable();
    }

    //查找按钮
    public void check(ActionEvent actionEvent) {
        // 1. 获取所有筛选条件
        Province selectedProvince = cobProvince.getSelectionModel().getSelectedItem();
        City selectedCity = cobCity.getSelectionModel().getSelectedItem();
        LocalDate selectedDate = datePicker.getValue();

        ArrayList<StatisticData> CheckList = new ArrayList<>();
        // 获取总行数
        int rowCount = tableView.getItems().size();

        // 通过索引遍历
        for (int i = 0; i < rowCount; i++) {
            StatisticData rowData = tableView.getItems().get(i);
            Boolean checkProvince = (selectedProvince == null || rowData.getRowAqiData().getLocation().getProvince().getName().equals(selectedProvince.getName()));
            Boolean checkCity = (selectedCity == null || rowData.getRowAqiData().getLocation().getCity().getName().equals(selectedCity.getName()));
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            Boolean checkDate = (selectedDate == null || rowData.getRowAqiData().getTime().format(formatter).equals(selectedDate.format(formatter)));
            if(checkProvince && checkCity  && checkDate )
            {
                CheckList.add(rowData);
            }
        }

        ObservableList<StatisticData> tableData = FXCollections.observableArrayList(CheckList);

        tableView.setItems(tableData);

    }

    // 初始化TableView列
    private void initializeTableColumns() {
        colId.setCellValueFactory(cellData -> {
            int rowNumber = cellData.getTableView().getItems().indexOf(cellData.getValue()) + 1;
            return new SimpleStringProperty(String.valueOf(rowNumber));
        });

        colProvince.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getRowAqiData().getLocation().getProvince().getName()));

        colCity.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getRowAqiData().getLocation().getCity().getName()));

        colLevel.setCellValueFactory(cellData ->
                new SimpleStringProperty(switchAqiLevel(cellData.getValue().getAccurateAqiData().getAccurateAqiLevel())));

        colDate.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getRowAqiData().getTime().toString()));

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        colTime.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getRowAqiData().getTime().format(formatter))); // 或者格式化时间

        String selectnepgName = "user" + String.valueOf((int)(Math.random() * 100) + 1);
        colNEPG.setCellValueFactory(cellData ->
                new SimpleStringProperty(selectnepgName));

        colNEPS.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getRowAqiData().getUser().getUsername()));

        //详情按钮
        colDetail.setCellFactory(cols->new TableCell<>(){
            private Button btn = new Button("操作");
            {
                btn.setOnAction(e->{
                    StatisticData user = getTableView().getItems().get(getIndex());
                    // 获取当前行索引
                    int rowIndex = getIndex();
                    GirdOperator_DetailController.NEPMsetSelectedStatisticData(user,rowIndex + 1,selectnepgName);
                    MyUtils.navigateToView(e,"group/nepm/publicSuperviseDataManagement/view/ConfirmAqiData_Detial.fxml");
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty?null:btn);
            }
        });

    }
    // 加载数据到TableView
    private void loadDataToTable() {
        ArrayList<StatisticData> NEPSuserList = MyUtils.readFileToArrayList("group/data/statistic_data_arraylist.dat");

        ObservableList<StatisticData> tableData = FXCollections.observableArrayList(NEPSuserList);

        tableView.setItems(tableData);
    }

    public void adminOut(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/common/view/NEPMLoginView.fxml");
    }
    public void toPublicSuperviseDataList(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/publicSuperviseDataManagement/view/PublicSuperviseDataList.fxml");
    }
    public void toConfirmAqiDataList(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/publicSuperviseDataManagement/view/ConfirmAqiDataList.fxml");
    }
    public void toProvinceStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/provinceStatistic.fxml");
    }
    public void toAqiDistributionStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/aqiDistributionStatistic.fxml");
    }
    public void toAqiTendencyStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/aqiTendencyStatistic.fxml");
    }
    public void toOtherDataStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/otherDataStatistic.fxml");
    }

    //将AqiLevel枚举转换为对应的等级
    private String switchAqiLevel(AccurateAqiLevel level) {
        int key = level.ordinal()+1;
        String AQILevel = "";
        switch (key){
            case 1:{
                AQILevel = "一级 优";
                break;
            }
            case 2:{
                AQILevel = "二级 良";
                break;
            }
            case 3:{
                AQILevel = "三级 轻度污染";
                break;
            }
            case 4:{
                AQILevel = "四级 中度污染";
                break;
            }
            case 5:{
                AQILevel = "五级 重度污染";
                break;
            }
            case 6:{
                AQILevel = "六级 严重污染";
                break;
            }

        }
        return AQILevel;

    }

}
